import { loginAPI, getUserInfoAPI } from '@/api/user'
import { contantsRoutes, resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
export default {
  // 开启命名空间
  namespaced: true,
  state() {
    return {
      token: getToken(),
      userInfo: {},
      menuList: [...contantsRoutes]
    }
  },
  mutations: {
    // 重置路由表
    resetMenu(state) {
      // 重置左侧菜单
      state.menuList = contantsRoutes
      // 重置路由系统
      resetRouter()
    },
    // 设置菜单列表
    setMenuList(state, filterRoutes) {
      state.menuList = [...state.menuList, ...filterRoutes]
    },
    setToken(state, token) {
      setToken(token)
      state.token = token
    },
    removeToken(state) {
      removeToken()
      state.token = ''
    },
    // 设置用户信息
    setUserInfo(state, payload) {
      state.userInfo = payload
    }
  },
  actions: {
    // 登录
    async login(context, payload) {
      const data = await loginAPI(payload)
      // console.log(data)
      context.commit('setToken', data.data.token)
    },
    // 获取用户信息
    async getUserInfo(context) {
      const data = await getUserInfoAPI()
      // console.log(data)
      context.commit('setUserInfo', data.data)
      return data.data.permissions
    },
    // 退出登录
    logout(context) {
      context.commit('setUserInfo', {})
      context.commit('removeToken')
      this.$store.commit('menu/resetMenu')
    }
  }
}
